/*
 * Copyright (C) 2021 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.gehj.androidlibs.Utils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ContentUris;
import android.content.Context;
import android.content.ContextWrapper;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ListAdapter;
import android.widget.ListView;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;



import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {

    public final static Integer PAGESIZE = 10;
    public final static Integer HOMEPAGE = 1;
    public final static String TYPE_NEWS = "news";
    public final static String TYPE_INDUSTRY = "industry";
    public final static String TYPE_SUPPORT = "support";
    public final static String TYPE_CORE = "core";
    public final static String TYPE_APPEARANCE = "appearance";
    public final static String TYPE_DEMONSTRATION = "demonstration";
    public final static String TYPE_PRODUCT = "product";

    public final static Integer BRIEF_SHOW = 1001;
    public final static Integer LEADER_SHOW = 1002;
    public final static Integer ORGANIZE_SHOW = 1003;
    public final static Integer ABOUTUS_SHOW = 1004;


    public final static Integer WORK_SHOW = 1;
    public final static Integer CIVILIZATION_SHOW = 1011;
    public final static Integer ACTIVITIES_SHOW = 2;

    public final static int TIMER_COUNT = 60000;
    public final static int TYPERETURN_DETAIL = 100001;

    //0：测风装置；1：自动风窗；2：自动风门；3：单独风速传感器；4：智能局部通风机系统' 5:22202工作面通风智能管控系统; 6:2¯²煤主运巷灾变风流应急控制系统
    public final static int OPERATION_WIND = 0;
    public final static int OPERATION_WINDOW = 1;
    public final static int OPERATION_GATE = 2;
    public final static int OPERATION_MODELSENSOR= 3;
    public final static int OPERATION_LOCAL= 4;
    public final static int OPERATION_WORKINGSURFACE = 5;
    public final static int OPERATION_MAINTUNNEL = 6;
    public final static int PLAY_HIK_STREAM_CODE = 1001;
    public final static int PLAY_HIK_STREAM_CODE_2 = 1002;
    public static final int[]  CHART_COLORS= {
            Color.rgb(192, 255, 140), Color.rgb(255, 247, 140), Color.rgb(255, 208, 140),
            Color.rgb(140, 234, 255), Color.rgb(150, 220, 157), Color.rgb(125, 190, 157),
            Color.rgb(140, 254, 255), Color.rgb(80, 200, 157), Color.rgb(125, 190, 197),
            Color.rgb(140, 254, 255), Color.rgb(80, 200, 157), Color.rgb(125, 190, 197),
            Color.rgb(140, 254, 255), Color.rgb(80, 200, 157), Color.rgb(125, 190, 197),
            Color.rgb(140, 254, 255), Color.rgb(80, 200, 157), Color.rgb(125, 190, 197),
            Color.rgb(140, 254, 255), Color.rgb(80, 200, 157), Color.rgb(125, 190, 197),
            Color.rgb(140, 254, 255), Color.rgb(80, 200, 157), Color.rgb(125, 190, 197)
    };

    public final static int SAVECODE = 201;
    public final static int DXF_READ_CODE = 1;

    /**
     * 列表集合
     */
    public static final int TYPE_LIST = 1;
    /**
     * 网格集合
     */
    public static final int TYPE_GRID = 2;
    //服务状态码 及路径
    public enum TypeNums {
        news_0(1, "news", "分院要闻"),
        industry_1(2, "industry", "行业动态"),
        support_2(3, "support", "支撑平台"),
        core_3(4, "core", "核心技术"),
        demonstration_4(5, "product", "示范工程"),
        product_5(6, "demonstration", "自主产品"),
        appearance_6(7, "appearance", "安全风采");

        public Integer getCode() {
            return code;
        }

        public String getType() {
            return type;
        }

        public String getName() {
            return name;
        }

        public void setCode(Integer code) {
            this.code = code;
        }

        public void setType(String type) {
            this.type = type;
        }

        public void setName(String name) {
            this.name = name;
        }

        private Integer code;
        private String type;
        private String name;

        TypeNums(Integer code, String type, String name) {
            this.code = code;
            this.type = type;
            this.name = name;
        }

        public static TypeNums getNameByType(String type) {
            return type.equals(news_0.getType()) ? news_0 :
                    type.equals(industry_1.getType()) ? industry_1 :
                            type.equals(support_2.getType()) ? support_2 :
                            type.equals(core_3.getType()) ? core_3 :
                                    type.equals(demonstration_4.getType()) ? demonstration_4 :
                                            type.equals(product_5.getType()) ? product_5 :
                                            type.equals(appearance_6.getType()) ? appearance_6 : news_0;

        }
    }

    @SuppressLint("SimpleDateFormat")
    public static String formatTime(long time, String format) {
        return new SimpleDateFormat(format).format(new Date(time));
    }

    @SuppressLint("SimpleDateFormat")
    public static String formatTime(Date time, String format) {
        // yyyy-MM-dd HH:mm:ss
        return new SimpleDateFormat(format).format(time);
    }

    /**
     * 格式化 yyyy-MM-dd HH:mm:ss
     *
     * @param time
     * @return
     */
    public static String formatTime(String time) {
        if (isEmpty(time)) {
            return "传入时间为空";
        }
        return formatTime(Long.parseLong(time), "yyyy-MM-dd HH:mm");
    }

    public static String formatTime(String time, String modle) {
        if (isEmpty(time)) {
            return "传入时间为空";
        }
        return formatTime(Long.parseLong(time), modle);
    }

    public static String formatHour(String time) {
        if (isEmpty(time)) {
            return "传入时间为空";
        }
        return formatTime(Long.parseLong(time), "HH:mm");
    }

    public static boolean isEmpty(List<?> list) {
        return (list == null || list.size() == 0);
    }

    public static boolean isEmpty(File file) {
        return file == null;
    }

    public static <T> boolean isEmpty(T[] array) {
        return ((array == null) || (array.length) == 0);
    }

    public static boolean isEmpty(String val) {
        if (val == null || val.matches("\\s") || val.length() == 0
                || "null".equalsIgnoreCase(val)) {
            return true;
        }
        return false;
    }

    public static <T> List<T> MapToList(Map<String, T> map) {
        List<T> list = new ArrayList<T>();
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String key = it.next();
            list.add(map.get(key));
        }
        return list;
    }

    public static boolean isMobileNum(String mobile) {
        if (isEmpty(mobile)) {
            return false;
        }
        Pattern p = Pattern.compile("^[1][3-8]+\\d{9}$");
        Matcher m = p.matcher(mobile);
        return m.matches();
    }

    /*
     * 判断是否是正确的电话号码格式
     */
    public static boolean isPhoneNum(String phone) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(17[0-9])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(phone);
        return m.matches();
    }

    public static boolean isServiceRunning(Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(30);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equalsIgnoreCase(
                    className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }



    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Bitmap getMyBitmap(String url){
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;
        try
        {
            in = new BufferedInputStream(new URL(url).openStream(), 1024);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, 1024);
            copy(in, out);
            out.flush();
            byte[] data = dataStream.toByteArray();
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            data = null;
            return bitmap;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    private static void copy(InputStream in, OutputStream out)
            throws IOException {
        byte[] b = new byte[1024];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }

    /**
     * @param @param  url
     * @param @param  width
     * @param @param  height
     * @param @return
     * @return Bitmap
     * @Des: 获取视频缩略图
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static Bitmap createVideoThumbnail(String url, int width, int height) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        int kind = MediaStore.Video.Thumbnails.MINI_KIND;
        try {
            if (Build.VERSION.SDK_INT >= 14) {
                retriever.setDataSource(url, new HashMap<String, String>());
            } else {
                retriever.setDataSource(url);
            }
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException ex) {
            // Assume this is a corrupt video file
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
                // Ignore failures while cleaning up.
            }
        }
        if (kind == Images.Thumbnails.MICRO_KIND && bitmap != null) {
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        }
        return bitmap;
    }

    /**
     * 主要是用于ListView的item同样是listView的情况
     *
     * @param @param listView
     * @return void
     * @Des:设置ListView的Adapter后调用此静态方法即可让ListView正确的显示在其父ListView的ListItem中。但是要注意的是，子ListView的每个Item必须是LinearLayout，不能是其他的，
     */

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
        float ratio = 1;
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawColor(Color.TRANSPARENT);

        canvas.drawRoundRect(rectF, bitmap.getWidth() / ratio,
                bitmap.getHeight() / ratio, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }

    /**
     * 通过url获取文件路径
     */
    public static String decodeUriAsFilePath(Context context, Uri uri) {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {"_data"};
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection,
                        null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                // Eat it
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    /**
     * 将bitmap图片压缩为临时图片文件
     *
     * @param bmp
     * @param file
     */
    public static void compressBmpToFile(Bitmap bmp, File file) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 80;// 个人喜欢从80开始,
        bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        while (baos.toByteArray().length / 1024 > 200) {
            baos.reset();
            options -= 10;
            bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据路径获得突破并压缩返回bitmap用于显示
     *
     * @param filePath
     * @return
     */
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(filePath, options);
    }

    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {    //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中

        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    /**
     * 计算图片的缩放值
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }

        return inSampleSize;
    }

    public static boolean equals(String s1, String s2) {
        if (s1 == null && s2 == null) return true;
        if (s1 == null) return false;
        if (s2 == null) return false;
        return s1.equals(s2);
    }

    /**
     * 判断两个字符串是否相等，忽略大小写
     *
     * @param s1
     * @param s2
     * @return
     */
    public static boolean equalsIgnoreCase(String s1, String s2) {
        if (s1 == null && s2 == null) return true;
        if (s1 == null) return false;
        if (s2 == null) return false;
        return s1.equalsIgnoreCase(s2);
    }

    /**
     * 截取指定长度字符串
     *
     * @param text
     * @param length
     * @param endWith
     * @return
     */
    public static String substring(String text, int length, String endWith) {
        int textLength = text.length();
        int byteLength = 0;
        StringBuffer returnStr = new StringBuffer();
        for (int i = 0; i < textLength && byteLength < length * 2; i++) {
            String str_i = text.substring(i, i + 1);
            if (str_i.getBytes().length == 1) {//英文
                byteLength++;
            } else {//中文
                byteLength += 2;
            }
            returnStr.append(str_i);
        }
        try {
            if (byteLength < text.getBytes("GBK").length) {//getBytes("GBK")每个汉字长2，getBytes("UTF-8")每个汉字长度为3
                returnStr.append(endWith);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return returnStr.toString();
    }


    public static File saveBitmapFile(Bitmap bitmap){
        File file = null;
        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
           Log.e("sdf", "SD卡不存在");
        }else {
             file=new File(Environment.getExternalStorageDirectory() + "/mybitmap/", System.currentTimeMillis() + ".jpg");//将要保存图片的路径


            try {
                Log.e("<<",file.getName());
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return file;
    }

    public static String[] splitString(String s){
        String[] strArray = null;
        strArray = s.split("/");
        return strArray;
    }


    public List<Bitmap> myFiles = new ArrayList<>();

    public  void  setMyFiles( List<Bitmap> lists){
        myFiles = lists;
    }

    public void delFromMyFiles(int postion){
        myFiles.remove(postion);
    }

    public List<Bitmap> getMyFiles(){
        return myFiles;
    }


    public static File saveBitmap(Bitmap bm) {
        File file = new File(Environment.getExternalStorageDirectory()
                + "/myimage/");
       File targetFile = new File(file,String.valueOf(System.currentTimeMillis()) + ".jpg");
        if(!file.exists()){
            file.mkdirs();
        }

        try {
            FileOutputStream out = new FileOutputStream(targetFile);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();

            Log.d("po", "已经保存");
            return targetFile;
        } catch (Exception e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static Activity findActivity(Context context)
    {
        if (context instanceof Activity)
        {
            return (Activity) context;
        }
        if (context instanceof ContextWrapper)
        {
            ContextWrapper wrapper = (ContextWrapper) context;
            return findActivity(wrapper.getBaseContext());
        } else {
            return null;
        }
    }



    // 根据数据库整形值返回 是  否
    public static String getBString_Integer(Integer val){
        if(val != null && val == 1)
            return "是";
        else
            return "否";
    }
    // 根据数据库boolean值返回 是  否
    public static String getBString_Boolean(Boolean val){
        if(val != null && val)
            return "是";
        else
            return "否";
    }
    // 根据boolean 返回数据需要的类型Integer
    public static Integer getI_Boolean(Boolean val){
        if(val)
            return 1;
        else
            return 0;
    }
    // 根据数据库整形值 返回boolean
    public static Boolean getB_Integer(Integer val){
        if(val != null && val == 1)
            return true;
        else
            return false;
    }
    // 根据数据库Boolean值 返回boolean
    public static Boolean getB_Boolean(Boolean val){
        if(val != null && val)
            return true;
        else
            return false;
    }
    // 根据数据库Double值 返回String
    public static String  getS_Double(Double val){
        if(val != null)
            return String.valueOf(val);
        else
            return "";
    }
    // 根据数据库Integer值 返回String
    public static String  getS_Integer(Integer val){
        if(val != null)
            return String.valueOf(val);
        else
            return "";
    }
    // 根据String值 返回数据库Integer
    public static Integer  getI_String(String val){
        if(val.equals(""))
            return null;
        else
            return Integer.valueOf(val);
    }
    // 根据String值 返回数据库Double
    public static Double  getD_String(String val){
        if(val.equals(""))
            return null;
        else
            return Double.valueOf(val);
    }




    public static InputStream getInputStream(final Context context,String filepath) {
        File file = new File(filepath);
        FileInputStream fileInputStream = null;


        try {

            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        /*try {
           // boolean flag = file.exists();
            if(!file.exists()){
                file.createNewFile();
            }
            file = new File(filepath);
           // boolean flag2 = file.canRead();
           // file.setReadable(true);
           // boolean flag3 = file.canRead();

            fileInputStream = new FileInputStream(filepath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/


        return fileInputStream;
               // getString(context, fileInputStream);
    }



    public static String getString(final Context context,InputStream inputStream) {
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "gbk");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer sb = new StringBuffer("");
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 获得文件路径
     * @param context The context.
     * @param uri The Uri to query.
     * @author paulburke
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static String readExternal(Context context,String FilePath)  {
        String content = "";
        InputStream instream = null;
        File file = new File(FilePath);
        try {
            instream = new FileInputStream(file);
            if (instream != null) {
                InputStreamReader inputreader
                        = new InputStreamReader(instream, "UTF-8");

                BufferedReader buffreader = new BufferedReader(inputreader);
                String line = "";
                //分行读取
                while ((line = buffreader.readLine()) != null) {
                    content += line + "\n";
                }
                instream.close();//关闭输入流
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return content;
    }




}
